package com.itliang.utils.easyexcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.itliang.core.result.BaseResponse;
import com.itliang.core.result.ResultUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Excel导入导出工具类
 *
 * @author : liangzhuoyuan
 */
@Slf4j
public class EasyExcelUtils {
    public static <T> void writeExcel(List<T> data, Class tClass, String name, HttpServletResponse response) {
        try {
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String fileName = name + dateStr;
            //防止下载时中文乱码
            String encode = URLEncoder.encode(fileName, "utf-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //添加这个是防止前端拿不到Content-disposition
            response.setHeader("Content-Disposition", "attachment;filename=" + encode + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), tClass)
                    .autoCloseStream(Boolean.FALSE).sheet(name)
                    .doWrite(data);
        } catch (Exception e) {
            log.error("文件导出失败,错误信息{}", e);
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            // TODO 修改自定义前端返回提示信息
            BaseResponse<?> r = ResultUtils.error(44444444, "Excel导出失败！");
            try {
                response.getWriter().println(JSON.toJSONString(r));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

}
